import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN, USER_INFO, MENU_LIST } from '@/store/mutation-types'
import router from '@/router/index'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 6000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    } else
      if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
        notification.error({
          message: 'Unauthorized',
          description: 'Authorization verification failed'
        })
        if (token) {
          store.dispatch('Logout').then(() => {
            setTimeout(() => {
              window.location.reload()
            }, 1500)
          })
        }
      }
  } else {
    notification.error({
      message: '网络错误或请求超时'
    })
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['easyWishCToken'] = token
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  const {
    rtn,
    msg,
    errCode
  } = response.data
  if (response.config?.headers?.isDownload) {
    if (!rtn) return response
  }
  if (rtn === '1') {
    return response.data
  } else {
    switch (errCode) {
      case '10001':
        notification.error({
          message: '服务内部错误'
        })
        break
      case '10002':
        notification.error({
          message: msg
        })
        break
      case '10003':
        notification.error({
          message: 'token过期'
        })
        storage.set(ACCESS_TOKEN, '')
        storage.set(USER_INFO, '')
        storage.set(MENU_LIST, [])
        router.push({ name: 'login' })
        break
      case '10004':
        notification.error({
          message: '账户已冻结，请联系管理员'
        })
        storage.set(ACCESS_TOKEN, '')
        storage.set(USER_INFO, '')
        storage.set(MENU_LIST, [])
        router.push({ name: 'login' })
        break
      case '10005':
        notification.error({
          message: '权限错误'
        })
        break
      default:
        break
    }
    return Promise.reject(msg)
  }
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
